package com.steve.xfood.controller;

import com.steve.xfood.config.ProjectUrlConfig;
import com.steve.xfood.enums.ResultEnum;
import com.steve.xfood.exception.XFoodException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 微信相关
 * @author steve
 * @date 2020/5/13 14:45
 */
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WeChatController {
    /**
     * 注入WxMpService配置
     */
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxMpService wxOpenService;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    /**
     * 微信公众平台授权
     * @param returnUrl 回调地址
     * @return
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        //1.配置
        //2.调用方法,构造网页授权url
        //设置获取url，访问userInfo方法
        //下面代码构造的是目的是为了获取code
        String url = projectUrlConfig.getWechatMpAuthorize() + "/sell/wechat/userInfo";
        String redirectUrl = null;
        try {
            redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("【微信网页授权】returnUrl编码异常,{}", e);
        }
        log.info("【微信网页授权 】 获取code redirectUrl={}",redirectUrl);
        //3.重定向到userInfo方法
        return "redirect:" + redirectUrl;
    }

    /**
     * 微信公众平台获取用户code
     * @param code
     * @param returnUrl
     * @return
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        //获取access token
        log.info("【微信网页授权】 code={}", code);
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new XFoodException(ResultEnum.WECHAT_OAUTH_ERROR.getCode(),e.getError().getErrorMsg());
        }
        //获取openid
        String openId = wxMpOAuth2AccessToken.getOpenId();
        //returnUrl一定要加上http://，不然会重定向跳转失败
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    /**
     * 微信开放平台授权
     * @param returnUrl
     * @return
     */
    @GetMapping("/qrAuthorize")
    public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) {
        String url = projectUrlConfig.getWechatOpenAuthorize() + "/sell/wechat/qrUserInfo";
        String redirectUrl = null;
        try {
            redirectUrl = wxOpenService.buildQrConnectUrl(url, WxConsts.QrConnectScope.SNSAPI_LOGIN, URLEncoder.encode(returnUrl,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("【微信网页授权】returnUrl编码异常,{}", e);
        }
        return "redirect:" + redirectUrl;
    }

    /**
     * 微信开放平台获取用户code
     * 扫码登录访问路径：
     * https://open.weixin.qq.com/connect/qrconnect?appid=wx6ad144e54af67d87&redirect_uri=http://sell.springboot.cn/sell/qr/oTgZpwdZi_KC40hZHU-YmlWogkHU&response_type=code&scope=snsapi_login&state=http://xfood.nat300.top/sell/wechat/qrUserInfo
     * @param code
     *
     * @return
     */
    @GetMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        //获取access token
        log.info("【微信网页授权】 code={}", code);
        try {
            wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new XFoodException(ResultEnum.WECHAT_OAUTH_ERROR.getCode(),e.getError().getErrorMsg());
        }
        log.info("wxMpOAuth2AccessToken={}",wxMpOAuth2AccessToken);
        //获取openid
        String openId = wxMpOAuth2AccessToken.getOpenId();
        //这里需要写死跳转到用户登录方法，不然无法实现功能
        String returnUrl = projectUrlConfig.getWechatOpenAuthorize() + "/sell/seller/login";
        //获取的是用户的openid
        return "redirect:" + returnUrl + "?openid=" + openId;
    }
}
